const jwt = require('jsonwebtoken')

const { JWT_SECRET } = require('../config/config.default')
const auth = async (ctx, next) => {
    const { access_token } = ctx.request.header
    // const token = authorization.replace('Bearer', '')
    const token = access_token
    try {
        const user = jwt.verify(token, JWT_SECRET)
        ctx.state.user = user
    } catch (error) {
        switch (error.name) {
            case 'TokenExpiredError':
                console.error('token已过期')
                ctx.body = {
                    code: -99,
                    message: 'token已过期',
                }
                return
            case 'JsonWebTokenError':
                ctx.body = {
                    code: -99,
                    message: 'token无效',
                }
                return
        }
    }
    await next()
}

module.exports = {
    auth
}